<template>
	<view class="min-h-screen">
		<!-- <uni-combox :candidates="candidates" placeholder="请输入物料编码" @confirm="confirm" v-model="material"></uni-combox> -->
		<view class="text-2xl font-bold mt-20 text-center">物料名称:{{materialName}}</view>
		<uni-easyinput class="uni-mt-5" trim="all" v-model="material" placeholder="请输入物料编码" @clear="clear"
			@confirm="confirm"></uni-easyinput>
		<view class="text-2xl font-bold mt-40">一：输入新产品编码选择物料</view>
		<view class="text-2xl font-bold">二：扫描二维码即可更换新的产品编码</view>
	</view>
</template>

<script setup>
	import {
		useGetScandata
	} from "@/hooks/index.js";
	import useKingdeeIsSuccess from "@/hooks/usekingdeeIsSuccess.ts";
	import {
		kingdeeQuery,
		kingdeeSave,
		kingdeeUnAudit,
		kingdeeView,
	} from "@/network/apis.ts";
	import {
		msg
	} from "@/utils/msg";

	import {
		formatTime,
		changeDataFormat
	} from '@/utils/util.js'

	// #ifdef APP-PLUS
	const {
		initListen,
		stopListen
	} = useGetScandata();

	initListen()

	//@ts-ignore
	uni.bus.on("scanCode", (message) => {
		uni.getNetworkType({
			complete: async (res) => {
				let networkType = res.networkType || "none";
				if (networkType === "none")
					return msg("当前无网络,请先检查您的网络状态");

				if (!materialID.value) return msg('请输入《新物料编码》后扫描！')
				controlKingdee(message);
			},
		});
	})

	onUnload(() => {
		stopListen();
		//@ts-ignore
		uni.bus.off("scanCode");
	});
	// #endif

	const material = ref()
	const materialName = ref()
	const materialID = ref()
	const CPZXBZ = ref()

	const candidates = []


	const clear = () => {
		materialName.value = ''
		materialID.value = ''
		CPZXBZ.value = ''
	}
	const confirm = async (e) => {

		const {
			data: res
		} = await kingdeeQuery({
			formId: "BD_MATERIAL",
			fieldKeys: `FName,F_BLU_CPZXBZ.FDataValue as CPZXBZ,FMATERIALID`,
			filterString: `FNumber  = '${e}' AND FUseOrgId.FNumber = '${uni.ORGNUMBER}'`,
			limit: '1'
		});

		const Result = useKingdeeIsSuccess("GET", res);
		console.log(Result);
		if (Result.length == 0) return msg('未获取到该物料信息！')
		materialName.value = Result[0]?.FName
		materialID.value = Result[0]?.FMATERIALID
		CPZXBZ.value = Result[0]?.CPZXBZ
	}

	// 先通过扫描的条码查入库记录表，更换表中条码，加上更换标识。编辑保存
	const controlKingdee = async (message) => {

		const haveLink = message.indexOf("barcode=");

		const trimmedCode =
			haveLink == -1 ? message : message.split("barcode=")[1];

		console.log(trimmedCode);

		const {
			data: res2
		} = await kingdeeQuery({
			formId: "BPL_InStockUpload",
			fieldKeys: `FID,FEntity_FENTRYID,FBPL_BarCode`,
			filterString: `FBPL_BarCode like '%${trimmedCode}%'`,
		})

		const value = useKingdeeIsSuccess("GET", res2);

		if (value.length == 0) return msg("未找到该条码入库记录");

		const {
			data: auditres
		} = await kingdeeUnAudit({
			formid: "BPL_InStockUpload",
			data: {
				Ids: value[0]["FID"],
			},
		});

		if (!auditres.Result.ResponseStatus.IsSuccess) {
			return useKingdeeIsSuccess("POST", auditres);
		}

		const newCode = trimmedCode.replace(
			trimmedCode.split("|")[3],
			materialID.value
		);
		const {
			data: saveRes
		} = await kingdeeSave({
			formid: "BPL_InStockUpload",
			data: {
				IsAutoSubmitAndAudit: true,
				IsDeleteEntry: false,
				NeedUpDateFields: ["FID", "FEntity", "FBPL_Cancel"],
				Model: {
					FID: value[0]["FID"],
					FEntity: [{
						FEntryID: value[0]["FEntity.FENTRYID"],
						FBPL_Cancel: true,
					}],
				},
			},
		});

		if (!saveRes.Result.ResponseStatus.IsSuccess) {
			return useKingdeeIsSuccess("POST", saveRes);
		}

		const FEntity = [{
			FMaterialId: {
				FMaterialId: materialID.value,
			},
			FCustId: {
				FCustId: newCode.split("|")[4],
			},
			FBPL_Weight: newCode.split("|")[5] / 100,
			FBPL_Machine: newCode.split("|")[1],
			FBPL_ProduceDate: changeDataFormat(newCode.split("|")[7]),
			FBPL_Datetime: formatTime(new Date().getTime()),
			FBPL_BarCode: newCode,
		}]

		console.log(FEntity);
		const {
			data: saveRes2
		} = await kingdeeSave({
			formid: "BPL_InStockUpload",
			data: {
				IsAutoSubmitAndAudit: true,
				Model: {
					FOrgId: {
						FNumber: uni.ORGNUMBER,
					},
					FEntity
				},
			},
		});
		console.log(saveRes2);
		if (saveRes2.Result.ResponseStatus.IsSuccess == true) {
			printText({
				code: newCode,
			});
		} else {
			msg(saveRes2.Result.ResponseStatus.Errors[0].Message);
		}

	};

	//入库成功再打印
	const printText = ({
		code
	}) => {
		const contents = [{
				align: "center",
				fontSize: "80",
				type: "TEXT",
				content: "合格证",
			},
			{
				type: "QR",
				align: "center",
				// height: 50,
				content: code,
			},
			{
				align: "left",
				type: "TEXT",
				fontSize: "35",
				content: `产品名称：${materialName.value}`,
			},
			{
				align: "left",
				type: "TEXT",
				fontSize: "35",
				content: `净重：${code.split("|")[5] / 100}KG`,
			},
			{
				align: "left",
				type: "TEXT",
				fontSize: "35",
				content: `执行标准：${CPZXBZ.value}`,
			},
			{
				align: "left",
				type: "TEXT",
				fontSize: "35",
				content: `生产日期：${code.split("|")[7]}`,
			},
			{
				align: "center",
				type: "TEXT",
				content: "\n\n" + `凯佳食品集团有限公司`,
			},
			{
				align: "center",
				type: "TEXT",
				fontSize: "18",
				content: `地址：临沂市河东区工业园温泉路779号`,
			},
			{
				align: "center",
				type: "TEXT",
				fontSize: "18",
				content: `电话：0539-8389677`,
			},
		];
		// console.log(contents);
		try {
			uni.pda.transactionPrinter({
					contents,
				},
				(res) => {
					if (res.msg === "Transaction print successful!") {
						msg("打印成功");
					}
				},
				(err) => {
					msg("打印失败，请重新打印！");
				}
			);
		} catch (error) {
			uni.showModal({
				title: "提示",
				content: "该设备不支持打印",
			});
		}
	};
</script>

<style>
	/* 可以添加样式 */
</style>